<template>
  <view class="fui-wrap page">
    <view class="page-content">
      <fui-form class="form" labelColor="#333333" labelWeight="bold" labelSize="28" labelRight="60" ref="form" top="0"
        :model="formData">
        <fui-form-item class="form-item" :class="{'form-item-disabled': isOrgAdmin}" asterisk label="姓名" :padding="['32rpx', '32rpx', '16rpx']" prop="name">
          <fui-input size="28" :padding="[0]" :borderBottom="false" placeholder="请输入姓名"
            v-model="formData.name" :disabled="isOrgAdmin"></fui-input>
        </fui-form-item>
        <fui-form-item :bottomBorder="false" class="form-item" label="头像" :padding="['32rpx', '32rpx', '16rpx']">
          <template #vertical>
            <upload-image class="form-upload" type="avatar" @uploaded="uploadedBusiness" :defaultList="formData.url ? [formData.url] : []"></upload-image>
          </template>
        </fui-form-item>
        <fui-form-item v-if="action !== 'add'" @click="isOrgAdmin ? showStatus = false : showStatus = true" arrow :class="{'form-item-disabled': isOrgAdmin}" asterisk label="人员状态"
          :padding="['32rpx', '32rpx', '16rpx']" prop="status">
          <fui-input size="28" :padding="[0]" :borderBottom="false" placeholder="请选择人员状态"
            v-model="formData.status" disabled></fui-input>
        </fui-form-item>
        <fui-form-item @click="showSex = true" arrow class="form-item" asterisk label="性别"
          :padding="['32rpx', '32rpx', '16rpx']" prop="sex">
          <fui-input size="28" disabled :padding="[0]" :borderBottom="false" placeholder="请选择性别"
            v-model="formData.sex"></fui-input>
        </fui-form-item>
        <fui-form-item class="form-item form-item-disabled" asterisk label="联系方式" :padding="['32rpx', '32rpx', '16rpx']" prop="mobile">
          <fui-input size="28" :padding="[0]" :borderBottom="false" placeholder="请输入联系方式"
            v-model="formData.mobile" :disabled="action !== 'add'"></fui-input>
        </fui-form-item>
        <!-- <fui-form-item class="form-item" asterisk label="初始密码" :padding="['32rpx', '32rpx', '16rpx']" v-if="action == 'add'" prop="password">
          <fui-input size="28" :padding="[0]" :borderBottom="false" placeholder="请输入初始密码"
            v-model="formData.password" disabled color="#999"></fui-input>
        </fui-form-item> -->
        <fui-form-item class="form-item" :class="{'form-item-disabled': isOrgAdmin}" asterisk label="身份证号" :padding="['32rpx', '32rpx', '16rpx']" prop="IDCard">
          <fui-input size="28" :padding="[0]" :borderBottom="false" placeholder="请输入身份证号"
            v-model="formData.IDCard" :disabled="isOrgAdmin"></fui-input>
        </fui-form-item>
        <fui-form-item @click="handleCheckAuthority" arrow class="form-item" :class="{'form-item-disabled': isOrgAdmin}" asterisk label="人员权限"
          :padding="['32rpx', '32rpx', '16rpx']" prop="authority">
          <fui-input size="28" disabled :padding="[0]" :borderBottom="false" placeholder="请选择人员权限"
            v-model="formData.authority"></fui-input>
        </fui-form-item>
        <fui-form-item v-if="isOrgDispatcher" @click="onClickAddressFun" arrow class="form-item" asterisk label="发货地"
          :padding="['32rpx', '32rpx', '16rpx']" prop="address">
          <fui-input size="28" disabled :padding="[0]" :borderBottom="false" placeholder="请选择发货地"
            v-model="formData.address"></fui-input>
        </fui-form-item>
        <view class="ui-page-tips">
          <fui-icon name="info-fill" size="28" color="#fcad4c"></fui-icon>本平台初始用户密码：姓名首字母+手机号后四位，如当前人员手机号已在本平台完成注册或有过邀约记录，请使用原有密码进行登录。
        </view>
        <view class="">
          <view class="submit-btn" v-if="action == 'add'">
            <fui-button @click="backPage" class="btn" width="42vw" height="78rpx" color="var(--fui-color-primary)" plain borderColor="var(--fui-color-primary)"
              text="取消"></fui-button>
            <fui-button class="btn" width="42vw" @click='submit("add")' height="78rpx" background="var(--fui-color-primary)"
              text="保存"></fui-button>
          </view>
          <view class="submit-btn" v-else>
            <fui-button v-if="isOrgAdmin" @click="backPage" class="btn" width="42vw" height="78rpx" color="var(--fui-color-primary)" plain borderColor="var(--fui-color-primary)"
              text="取消"></fui-button>
            <fui-button class="btn" @click='submit("update")' width="88%" height="78rpx" background="var(--fui-color-primary)"
              text="保存"></fui-button>
            <fui-button v-if="!isOrgAdmin" @click="deleteFun" class="btn" width="88%" height="78rpx" background="#FC5353"
              disabledBackground="#7E7E7E" disabledColor="#4D4D4D" text="删除"></fui-button>
          </view>
        </view>
      </fui-form>
      <!-- 性别 -->
      <fui-picker layer="1" @cancel="showSex = false" radius :options="sexList" :linkage="true" :show="showSex"
        @change="changeSex"></fui-picker>
      <!-- 人员状态 -->
      <fui-picker layer="1" @cancel="showStatus = false" radius :options="statusList" :linkage="true" :show="showStatus"
        @change="changeStatus"></fui-picker>
      <!-- 发货地 -->
      <fui-picker layer="1" @cancel="showAddress = false" radius :options="showAddressOptions" :linkage="true"
        :show="showAddress" @change="onAddressfirm"></fui-picker>
      <!-- 人员权限 -->
      <fui-select :show="showAuthority" maskClosable multiple :options="showAuthorityList" title="请选择人员权限"
        @confirm="onConfirm" @close="showAuthority = false"></fui-select>
      <fui-dialog :buttons="[
					{ text: '取消', color: '#999999' },
					{ text: '确定', color: '#FC5353' }
				]" :show="showDialog" :title="content" maskClosable @click="clickDialog"
        @close="showDialog = false"></fui-dialog>
    </view>
  </view>
</template>

<script setup>
  import { ref, inject, unref, computed, watch } from 'vue'
  import { onLoad, onShow } from '@dcloudio/uni-app'
  import { setTitle } from '@/utils/common'
  import { useStore } from 'vuex'
  import uploadImage from '@/components/upload/image'
  import staffApi from "@/api/staff"
	import { getDefaultPassword } from '@/utils/tools'

  const store = useStore();
  const tab = inject('$tab');
  const modal = inject('$modal');
  
  const props = defineProps({});
  const add = ref(false)
  const title = ref('人员信息');
  
  // 用户状态 0 在职 1 离职 2 停职
  const statusList = ref([{
      text: '在职',
      value: 0
    },
    {
      text: '离职',
      value: 1
    },
    {
      text: '停职',
      value: 2
    }
  ]);
  const sexList = ref([{
      text: '男',
      value: '1'
    },
    {
      text: '女',
      value: '2'
    }
  ]);
  const authorityList = ref([]);
  const showAuthorityList = ref([])

  // 获取人员权限
  const hasPerm = (code) => {
    const authorityStr = formData.value.authorityCode + ''
    return authorityStr.indexOf(code) > -1
  }

  const addressList = ref([])
  
  const showStatus = ref(false); //人员状态
  const showAuthority = ref(false); //人员权限
  const showAddress = ref(false); // 选择发货地
  const showSex = ref(false); //性别
  const showDialog = ref(false);
  //选择权限 如果是负责人 则不能修改
  const handleCheckAuthority = () => { 
    showAuthorityList.value = showAuthorityList.value.map((item => {
      return {
        ...item,
        checked: hasPerm(item.code)
      }
    }))
    showAuthority.value = !isOrgAdmin.value
  }

  const isOrgAdmin = computed(() => {
    return hasPerm('scm_gyl_yyjl') || hasPerm('scm_gysfzr')
  })

  const isOrgDispatcher = computed(() => {
    return !isOrgAdmin.value && (hasPerm('scm_gyl_fhgl') || hasPerm('scm_gysfhzy'))
  })
  
  // 获取供应链ID、公司部门id、用户id
  const conmpanyID = ref()  //供应链/供应商id
  const deptId = ref()  //部门id
  const userID = ref()  //用户id
  const action = ref()  //页面状态
  const adminName = ref() //管理人员姓名
  
  onLoad(async (option) => {
    await getRoleList() //权限列表
    deptId.value = store.getters.currentDeptId;  //部门id
    conmpanyID.value = store.getters.companyId  //供应链id
    action.value = option.action //是新增还是修改
    adminName.value = option.name //管理人员姓名
    if (option.action === 'add') {
      action.value = option.action  
      formData.value.status = '在职'
      formData.value.statusValue = 0
      setTitle('添加人员');
    }else{
      userID.value = option.userID //用户id
      setTitle('修改人员');
      getAdminUserInfoFun(userID.value)
    }
    getAddressListFun(conmpanyID.value) //发货地列表
  });
  
  // 确认状态
  const changeStatus = (e) => {
    showStatus.value = false;
    formData.value.status = e.text
    formData.value.statusValue = e.value
  };
  // 确认性别
  const changeSex = (e) => {
    formData.value.sex = e.text
    formData.value.sexValue = e.value
    showSex.value = false;
  };

  //校验规则
  const rules = computed(() => {
    const list = [
      {
        name: 'name',
        rule: ['required', 'minLength:2'],
        msg: ['请输入姓名', '姓名必须2个或以上字符']
      },
      {
        name: 'mobile',
        rule: ['required', 'isMobile'],
        msg: ['请输入手机号', '请输入正确的手机号']
      },
      {
        name: 'status',
        rule: ['required'],
        msg: ['请选择状态']
      },
      {
        name: 'IDCard',
        rule: ['required', "isIdCard"],
        msg: ['请输入身份证号', "请输入正确的身份证号码"]
      }
    ]
    // if (action.value === 'add') {
    //   list.push({
    //     name: 'password',
    //     rule: ['required', "isEnAndNo"],
    //     msg: ['请输入初始密码', "密码为英文和数字组合，不超过20个字符"]
    //   })
    // }
    if (isOrgDispatcher.value) { // 有发货管理权限
      list.push({
        name: 'addressValue',
        rule: ['required'],
        msg: ['请选择人员发货地']
      })
    }
    return list
  })

  //仅type=select时有效，返回选中的值, 人员权限提交
  const onConfirm = (e) => {
    for (let i = 0; i < e.options.length; i++) {
      if (i == 0) {
        formData.value.authority = e.options[i].name 
        formData.value.authorityValue = e.options[i].id
        formData.value.authorityCode = e.options[i].code
      } else {
        formData.value.authority += "," + e.options[i].name
        formData.value.authorityValue += "," + e.options[i].id
        formData.value.authorityCode += "," + e.options[i].code
      }
    }
    if(formData.value.authorityCode.includes('scm_gyl_fhgl') || formData.value.authorityCode.includes('scm_gysfhzy')){
      showAddressList.value = true
      if(!showAddressOptions.value.length){
        showAddressList.value = false
      }
    }else{
      formData.value.addressValue = ''
      formData.value.address = ''
    }
    
    showAuthority.value = false;
    
  };

  // 发货地址提交
  const onAddressfirm = (e) => {
      formData.value.address = e.text
      formData.value.addressValue = e.value
      showAddress.value = false
    
  }
  
  // 获取图片地址
  const uploadedBusiness = (e) => {
    formData.value.url = e[0]
  };

  const form = ref();
  const formData = ref({
    id:'',
    name: '',
    url: '',
    status: '', //人员状态名称
    statusValue: '',//人员状态id
    sex: '',
    sexValue: '',
    mobile: '',  //手机号
    // password: '', 
    IDCard: '', //身份证号
    authority: '', //权限
    authorityValue: '', //权限值
    authorityCode: '', //权限code
    address: '',  // 发货地址
    addressValue: '', // 发货地址id
  });

  // 匹配默认密码
  // watch(formData.value, (newValue) => {
	// 	if (action.value === 'add' && newValue.name && newValue.name.length >= 2 && newValue.mobile && newValue.mobile.length >= 11) {
	// 		formData.value.password = getDefaultPassword(newValue.name, newValue.mobile)
	// 	}
	// })
  
  //提交保存
  const submitFrom = ref()
  const submit = async (type) => {
    const ids = []
    authorityList.value.map(item => {
      if (formData.value.authorityCode.indexOf(item.code) > -1) {
        ids.push(item.id)
      }
    })
    if (!ids.length) {
      modal.msgError('请选择人员权限！')
      return
    }

    // 添加form
    submitFrom.value = {
      id: Number(userID.value),
      nickname: formData.value.name,
      deptId: deptId.value,
      mobile: formData.value.mobile,
      sex: store.getters.userType == 1 ? formData.value.sexValue : formData.value.sex,
      avatar: formData.value.url, //头像
      avator:formData.value.url, //头像
      // password: formData.value.password,
      // password: 'test111',
      roleIds: ids.join(','), //权限
      idCard: formData.value.IDCard,
      deliverPlaceId: formData.value.addressValue,
      status: store.getters.userType == 1 ? Number(formData.value.statusValue) : formData.value.status, //人员状态名称
      name:formData.value.name,
      phone: formData.value.mobile,
      // pwd: formData.value.password,
      // pwd: 'test111',
      idCardNum: formData.value.IDCard,
      permit: formData.value.authority, //权限
      supplierId: conmpanyID.value
    }
    const res = await form.value.validator(formData.value, rules.value)
    if (res.isPassed) {
      // modal.msg('校验通过！');
      if(type == "add"){
        addStaffFun(submitFrom.value)
      }else{
        updateAdminUserFun(submitFrom.value)
      }
    }
  };
 
  // 返回
  const backPage = () => {
    uni.navigateBack({
      delta: 1
    });
  };
   // 新增供应链/供应商员工
   const addStaffApiUrl = computed(() => {
     let apiUrl = ''
     if (store.getters.userType == 1) apiUrl = 'addSupplyStaff' // 新增供应链员工
     if (store.getters.userType == 2) apiUrl = 'addSupplierStaff' // 新增供应商员工
     return apiUrl
   })
   // api 新增员工
  const addStaffFun = (data) => {
    staffApi[addStaffApiUrl.value](data).then((res) => {
      if (res.code === 0) {
        modal.msg('添加成功')
        tab.navigateBack()
      } else {
        modal.msgError(res.msg);
      }
    });
 
  };
  // 修改供应链/供应商员工
  const getEditStaffApiUrl = computed(() => {
    let apiUrl = ''
    if (store.getters.userType == 1) apiUrl = 'updateSupplyStaff' // 修改供应链员工
    if (store.getters.userType == 2) apiUrl = 'updateSupplierStaff' // 修改供应商员工
    return apiUrl
  })
  // api 修改员工信息
  const updateAdminUserFun = (data) => {
    staffApi[getEditStaffApiUrl.value](data).then((res) => {
      if (res.code === 0) {
        modal.msg('修改成功')
        tab.navigateBack()
      } else {
        modal.msgError(res.msg);
      }
    });
  };
  
  // 获取供应链/供应商员工
  const getAdminUserInfoApiUrl = computed(() => {
    let apiUrl = ''
    if (store.getters.userType == 1) apiUrl = 'getAdminUserInfo' // 获取供应链员工
    if (store.getters.userType == 2) apiUrl = 'getSupplierAdminUserInfo' // 获取供应商员工
    return apiUrl
  })

  // 根据id获取权限code
  const getAuthorityCodeById = (ids) => {
    const codeArr = []
    authorityList.value.map(item => {
      if (ids.indexOf(item.id) > -1) {
        codeArr.push(item.code)
      }
    })
    return codeArr.join(',')
  }

  // api 获取员工信息
  const getAdminUserInfoFun = async (data) => {
    const res = await staffApi[getAdminUserInfoApiUrl.value](data)
   if (res.code === 0) {
     if(store.getters.userType == 2){
       await apiAddressName(conmpanyID.value, res.data.deliverPlaceId)
     }
     adminUserInfoFun(res.data)
   } else {
     modal.msgError(res.msg);
   }
  };
  const addressName = ref() //发货地名称
  const usedAddressList = ref([])
  const adminUserInfoFun = (data) => {
    formData.value.name = store.getters.userType == 1 ? data.nickname : data.name
    formData.value.url = store.getters.userType == 1 ? data.avatar : data.avator
    formData.value = {...formData.value}
    
    if(store.getters.userType == 1){
      formData.value.statusValue = data.status
      formData.value.status = data.status == 0 ? "在职" : data.status == 1 ? "离职" : "停职"
    }else{
      formData.value.status = data.status
      formData.value.statusValue = data.status == "在职" ? 0 : data.status == "离职" ? 1 : 2
    }
    
    formData.value.sexValue = data.sex
    formData.value.sex = store.getters.userType == 1 ? (data.sex == '1' ? '男' : '女' ) : data.sex
    formData.value.mobile =  store.getters.userType == 1 ? data.mobile : data.phone
    // formData.value.password = store.getters.userType == 1 ? data.password : data.pwd
    formData.value.IDCard = store.getters.userType == 1 ? data.idCard : data.idCardNum
    formData.value.authority = store.getters.userType == 1 ? data.roleNames : data.permit
    formData.value.authorityValue = data.roleIds
    formData.value.authorityCode = getAuthorityCodeById(data.roleIds)
    formData.value.addressValue = data.deliverPlaceId  //发货地id
    if(store.getters.userType == 1){
      formData.value.address = data.deliverPlaceName   // 发货地地址
    }else{
        formData.value.address = addressName.value // 发货地地址
    }
    // 确认发货地址是否有值
    if (formData.value.address) {
      usedAddressList.value = [{
        text: formData.value.address,
        value: formData.value.addressValue
      }]
    } else {
      showAddressList.value = false;
    }
    console.log('formData.value', formData.value)
  }

  const showAddressOptions = computed(() => {
    let list = addressList.value
    if (usedAddressList.value[0] && addressList.value.findIndex(item => item.value === usedAddressList.value[0].value) < 0) {
      list = addressList.value.concat(usedAddressList.value)
    }
    return list
  })
  
  // 权限列表
  const roleApi = computed(() => {
    let apiUrl = ''
    if (store.getters.userType == 1) apiUrl = 'getSupplyRoleList' // 获取供应链角色列表
    if (store.getters.userType == 2) apiUrl = 'getSupplierRoleList' // 获取供应商角色列表
    return apiUrl
  })
  const getRoleList = async () => {
    try {
      await staffApi[roleApi.value]().then((res) => {
        if (res.code === 0) {
          authorityList.value = res.data.map((item) => {
            return {
              ...item,
              text: item.name,
              value: item.code
            };
          });
          showAuthorityList.value = authorityList.value.filter(item => item.code !== 'scm_gyl_yyjl' && item.code !== 'scm_gysfzr')
        }
      })
    } catch (e) {
      modal.closeLoading();
    }
  }
  
  // 查询修改、新增供应链、供应商的发货地址列表
  const getAddressListApiUrl = computed(() => {
    let apiUrl = ''
    // if (action.value == 'add'){
      if (store.getters.userType == 1) apiUrl = 'getAddSupplyAddressList' // 供应链新增时，发货地为未绑定列表
      if (store.getters.userType == 2) apiUrl = 'getAddSupplierAddressList' // 供应商新增时，发货地为未绑定列表
    // }else{
    //   if (store.getters.userType == 1) apiUrl = 'getEditSupplyAddressList' // 供应链修改时，发货地为所有列表
    //   // if (store.getters.userType == 2) apiUrl = 'getEditSupplierAddressList' // 供应商修改时，发货地为所有列表
    //   if (store.getters.userType == 2) apiUrl = 'getAddSupplierAddressList' // 供应商新增时，发货地为未绑定列表
    // }
    return apiUrl
  })
  
  // 选择发货地的开关
  const showAddressList = ref(true)
  
  // api 发货地址列表
  const getAddressListFun = (id) => {
    const addressData = ref({
      pageNo: 1,
      pageSize: 100,
      id:id
    })
    staffApi[getAddressListApiUrl.value](addressData.value).then((res) => {
      if (res.code === 0) {
        if(store.getters.userType == 1){
          if(res.data.length != 0){
            addressList.value = res.data.map((item) => {
              return {
                ...item,
                text: item.deliveryPlace,
                value: item.id
              };
            });
          }
        }else{
          if(res.data.length != 0){
            addressList.value = res.data.map((item) => {
              return {
                ...item,
                text: item.deliveryPlace,
                value: item.id
              };
            });
          }
        }
      }
    })
  }
  
  // api 查发货地地址名称
  const apiAddressName = async (id,addressID) =>{
    const nameData = ref({
      pageNo: 1,
      pageSize: 100,
      id:id
    })
    await staffApi.getEditSupplierAddressList(nameData.value).then((res) => {
      if (res.code === 0) {
        addressName.value = res.data.list.find(item => item.id === addressID)?.deliveryPlace;
      }
    })
  }
  
  // 删除
  const content= ref()
  const deleteFun = () => {
    if(formData.value.name == adminName.value){
      modal.msg('管理员不可以删除！')
    }else{
      content.value = `确认要删除人员${formData.value.name}吗？`
      showDialog.value = true
    }
    
  }
  const clickDialog = (e) => {
    if (e.index === 0) {
      // 取消
      showDialog.value = false;
    } else {
      // 确认
      deleteUserFun()
      showDialog.value = false;
    }
  };
  // 删除供应链、供应商人员
  const deleteUserApiUrl = computed(() => {
    let apiUrl = ''
    if (store.getters.userType == 1) apiUrl = 'deleteSupplyUser' // 删除供应链 员工
    // if (store.getters.userType == 2) apiUrl = 'getSupplierChainUserStatistics' // 删除供应商 员工
    if (store.getters.userType == 2) apiUrl = 'deleteSupplierUser'
    return apiUrl
  })
  
  // api 删除员工
  const deleteUserFun = () => {
    try {
      staffApi[deleteUserApiUrl.value](userID.value).then((res) => {
        if (res.code === 0) {
          modal.msg('删除成功')
          uni.navigateTo({
            url: `/pages/company/index`,
          });
        }
      })
    } catch (e) {
      modal.closeLoading();
    }
  }
  // 点击选择发货地
  const onClickAddressFun = () => {
    if(showAddressList.value){
      showAddress.value = true
    }else{
      showAddress.value= false
      modal.msg('暂无可绑定的发货地！')
    }
  }
</script>

<style lang="scss" scoped>
  .page {
    background-color: #ffffff;
    min-height: 100%;

    :deep(.fui-form__msg-wrap) {
      z-index: 11000;
    }

    &-content {
      width: calc(100% - 60rpx);
      margin: 0 auto;
    }

    .upload-head {
      padding: 0;
      padding-top: 32rpx;

      .head-text {
        margin-bottom: 12rpx;
      }
    }

    ::v-deep .fui-upload__img {
      background-color: #f8f8f8 !important;
    }

    .submit-btn {
      display: flex;
      justify-content: space-between;
      width: 100%;
      margin-top: 100rpx;
    }

    .page-title {
      display: flex;
      justify-content: space-between;
      align-items: center;
      font-weight: bold;
      padding: 114rpx 0 8rpx;

      .back {
        margin-left: -8rpx;
        width: 10%;
      }
    }

    .form-upload {
      margin-left: 32rpx;
    }

    .form-item-disabled {
      ::v-deep .fui-input__disabled {
        color: #999 !important;
      }
    }
  }
</style>